import React, { useContext, useEffect, Component } from 'react';
import FieldContext from './FieldContext';

class Field extends Component {
  static contextType = FieldContext;

  constructor(props) {
    super(props);
    this.store = {};
  }

  componentDidMount() {
    // 初始化的时候注册 Field，返回卸载函数
    this.unregisterEntity = this.context.registerEntity(this);
  }

  componentWillUnmount() {
    if (this.unregisterEntity) {
      this.unregisterEntity();
    }
  }

  onStoreChange = () => {
    // 暴露一个强制更新的方法，在 表单值改变的时候(setFieldValue)调用
    this.forceUpdate();
  };

  getControlled = () => {
    const { getFieldValue, setFieldsValue } = this.context;
    const { name } = this.props;
    return {
      value: getFieldValue(name), // 数据应该从 formStore 中读取
      onChange: (e) => {
        const newVal = e.target.value;
        setFieldsValue({ [name]: newVal });
      },
    };
  };

  render() {
    const { children } = this.props;
    return React.cloneElement(children, this.getControlled());
  }
}

export default Field;
